package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("crmRealm")
public class CrmRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;



    //覆盖父类方法
    //设置新的匹配器 注入一个CredentialsMatcher器对象
    @Override
    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    //授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //数据库中拿到的对象
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        //AuthorizationInfo ---是接口,需要返回真实对象
        //获取当前登录的对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //判断是否超管  是的话给对象设置角色&权限
        if(employee.isAdmin()){
            info.addRole("admin");
            info.addStringPermission("*:*");
        }else{//给用户设置权限
            //通过员工id拿到角色
            List<String> rolesSn = roleMapper.getRolesSnByEmployeeId(employee.getId());
            //通过员工id拿到权限表达式
            List<String> expressions = roleMapper.getExpressionsByEmployeeId(employee.getId());
            info.addRoles(rolesSn);
            info.addStringPermissions(expressions);
        }

        return info;
    }
    //认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        //假设从数据库拿回来的是employee数据
//        Employee employee = new Employee();
//        employee.setName("zhangsan");
//        employee.setPassword("333");
        Object principal = token.getPrincipal();
        //从数据库拿数据
        Employee employee = employeeMapper.getEmployeeByName(principal.toString());
        if(employee != null){
            //加盐
            return new SimpleAuthenticationInfo(
                    employee,
                    employee.getPassword(),
                    ByteSource.Util.bytes(employee.getName()),
                    this.getName());
        }
        return null;
    }
}
